package api

import (
	__ "api_getway/basic/proto"
	"api_getway/config"
	"api_getway/handler/request"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddBook(c *gin.Context) {
	var err error
	var req request.AddBookReq

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	book, err := config.BookClient.AddBook(c, &__.AddBookReq{
		Title:   req.Title,
		TypesId: req.TypesId,
		Num:     req.Num,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "图书入库成功",
		"Id":   book.Id,
	})
}

func UpdateStatus(c *gin.Context) {
	var err error
	var req request.UpdateStatusReq

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	update, err := config.BookClient.UpdateStatus(c, &__.UpdateStatusReq{
		Id:     req.Id,
		Status: req.Status,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "图书状态修改成功",
		"Id":   update.Id,
	})
}

func DelBook(c *gin.Context) {
	var err error
	var req request.DelBookReq

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	_, err = config.BookClient.DelBook(c, &__.DelBookReq{
		Id: req.Id,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "图书删除成功",
	})
}

func BookList(c *gin.Context) {
	var err error
	var req request.BookList

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	list, err := config.BookClient.BookList(c, &__.BookListReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Title:    req.Title,
		TypesId:  req.TypesId,
		Status:   req.Status,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "图书列表展示成功",
		"list": list,
	})
}
